/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.edu.unal.bioingenium.kbmed.web.util;

import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * @author alejandro
 */
public class FacesUtils {

    private static HttpSession session;

    /**
     * 
     * @return
     */
    public static ServletContext getServletContext() {
        if (FacesContext.getCurrentInstance() != null) {
            return (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        } else if (session != null) {
            return session.getServletContext();
        } else {
            return null;
        }

    }

    /**
     * 
     * @param param
     * @return
     */
    public static String getInitParameter(String param) {
        if (FacesContext.getCurrentInstance() != null) {
            return ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getInitParameter(param);
        } else if (session != null) {
            return session.getServletContext().getInitParameter(param);
        } else {
            return null;
        }

    }
    private static final String PATH_SEPARATOR = "/";

    /**
     * 
     * @return
     */
    public static String getPersonalizedFilesPath() {
        String path = FacesUtils.getInitParameter("PERSONALIZEDFILEPATH");
        //Means the user defined an absolute path
        if (isAbsolutePath(path)) {
            return path;
        } else {
            //Means the user defined a relative path
            return getResourceFullPath(path);
        }
    }

    /**
     * 
     * @return
     */
    public static String getTempFilesPath() {
        String path = FacesUtils.getInitParameter("TEMPFILEPATH");
        //Means the user defined an absolute path
        if (isAbsolutePath(path)) {
            return path;
        } else {
            //Means the user defined a relative path
            return getResourceFullPath(path);
        }
    }

    private static boolean isAbsolutePath(String path) {
        return (path.startsWith(PATH_SEPARATOR) || path.indexOf(":") != -1);
    }

    /**
     * 
     * @return
     */
    public static FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

    /**
     * 
     * @param beanName
     * @return
     */
    public static Object getManagedBean(String beanName) {
        if (FacesContext.getCurrentInstance() != null) {
            return FacesContext.getCurrentInstance().getApplication().getVariableResolver().resolveVariable(
                    FacesContext.getCurrentInstance(),
                    beanName);
        } else if (session != null) {//Returns the session Bean from Servlet Context
            return session.getAttribute(beanName);
        } else {
            return null;
        }
    }

    
    /**
     * 
     * @param beanName
     * @param managedBean
     */
    public static void setManagedBeanInSession(String beanName,
            Object managedBean) {
        if (FacesContext.getCurrentInstance() != null) {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(beanName, managedBean);
        } else if (session != null) {
            session.setAttribute(beanName, managedBean);
        }
    }

    /**
     * 
     * @param name
     * @return
     */
    public static String getRequestParameter(String name) {
        return (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(
                name);
    }

    /**
     * 
     * @param name
     */
    public static void clearRequestParameter(String name) {
        FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().remove(name);
    }

    /**
     * 
     * @return
     */
    public static HttpServletResponse getHttpServletResponse() {
        return (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    }

    /**
     * 
     * @return
     */
    public static Map getRequestCookieMap() {
        return FacesContext.getCurrentInstance().getExternalContext().getRequestCookieMap();
    }

    /**
     * 
     * @return
     */
    public static String getRemoteHost() {
        return ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getRemoteHost();
    }

    /**
     * 
     * @param msg
     */
    public static void addInfoMessage(String msg) {
        addInfoMessage(null, msg);
    }

    /**
     * 
     * @param clientId
     * @param msg
     */
    public static void addInfoMessage(String clientId, String msg) {
        FacesContext.getCurrentInstance().addMessage(clientId,
                new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg));
    }

    /**
     * 
     * @param summary
     * @param detail
     */
    public static void addErrorMessage(String summary, String detail) {
        addErrorMessage(null, summary, detail);
    }

    /**
     * 
     * @param clientId
     * @param summary
     * @param detail
     */
    public static void addErrorMessage(String clientId, String summary, String detail) {
        FacesContext.getCurrentInstance().addMessage(clientId,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail));
    }

    

    private static Application getApplication() {
        ApplicationFactory appFactory = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
        return appFactory.getApplication();
    }

   

    private static String getJsfEl(String value) {
        return "#{" + value + "}";
    }

    /**
     * 
     * @param key
     * @return
     */
    public static String getMessageByKey(String key) {
        String messageBundleName = FacesContext.getCurrentInstance().getApplication().getMessageBundle();
        ResourceBundle resourceBundle = ResourceBundle.getBundle(messageBundleName);

        try {
            return resourceBundle.getString(key);
        } catch (Exception e) {
            return key;
        }

    }

    /**
     * 
     * @return
     */
    public static Locale getCurrentUserLocale() {
        return FacesContext.getCurrentInstance().getViewRoot().getLocale();
    }

    /**
     * 
     * @param value
     * @return
     */
    public static boolean isBindingExpression(Object value) {
        return (value != null && value instanceof String && ((String) value).startsWith("#{") && ((String) value).endsWith("}"));
    }

    /**
     * 
     * @param resourceRelativePathy
     * @return
     */
    public static String getResourceFullPath(String resourceRelativePathy) {
        return getServletContext().getRealPath(resourceRelativePathy);
    }

    /**
     * 
     * @param newLocale
     */
    public static void changeLanguageLocale(Locale newLocale) {
        FacesContext.getCurrentInstance().getViewRoot().setLocale(newLocale);
    }

    /**
     * 
     * @return
     */
    public static HttpSession getSession() {
        return session;
    }

    /**
     * 
     * @param session
     */
    public static void setSession(HttpSession session) {
        FacesUtils.session = session;
    }
}
